{"componentChunkName":"component---src-templates-post-jsx","path":"/[BOJ]2146/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"abc306b3-c3a6-552a-8979-e82d506b3921","excerpt":"문제 여러 섬으로 이루어진 나라가 있다. 이 나라의 대통령은 섬을 잇는 다리를 만들겠다는 공약으로 인기몰이를 해 당선될 수 있었다. 하지만 막상 대통령에 취임하자, 다리를 놓는다는 것이 아깝다는 생각을 하게 되었다. 그래서 그는, 생색내는 식으로 한 섬과 다른 섬을 잇는 다리 하나만을 만들기로 하였고, 그 또한 다리를 가장 짧게 하여 돈을 아끼려 하였다.…","html":"<h2>문제</h2>\n<p>여러 섬으로 이루어진 나라가 있다. 이 나라의 대통령은 섬을 잇는 다리를 만들겠다는 공약으로 인기몰이를 해 당선될 수 있었다. 하지만 막상 대통령에 취임하자, 다리를 놓는다는 것이 아깝다는 생각을 하게 되었다. 그래서 그는, 생색내는 식으로 한 섬과 다른 섬을 잇는 다리 하나만을 만들기로 하였고, 그 또한 다리를 가장 짧게 하여 돈을 아끼려 하였다.</p>\n<p>이 나라는 N×N크기의 이차원 평면상에 존재한다. 이 나라는 여러 섬으로 이루어져 있으며, 섬이란 동서남북으로 육지가 붙어있는 덩어리를 말한다.</p>\n<img src='https://www.acmicpc.net/JudgeOnline/upload/201008/bri.PNG' width='50%'>\n<p>그림에서 색이 있는 부분이 육지이고, 색이 없는 부분이 바다이다. 이 바다에 가장 짧은 다리를 놓아 두 대륙을 연결하고자 한다. 가장 짧은 다리란, 다리가 격자에서 차지하는 칸의 수가 가장 작은 다리를 말한다. 다음 그림에서 두 대륙을 연결하는 다리를 볼 수 있다.</p>\n<img src='https://www.acmicpc.net/JudgeOnline/upload/201008/b2.PNG' width='50%'>\n<p>물론 위의 방법 외에도 다리를 놓는 방법이 여러 가지 있으나, 위의 경우가 놓는 다리의 길이가 3으로 가장 짧다(물론 길이가 3인 다른 다리를 놓을 수 있는 방법도 몇 가지 있다). 지도가 주어질 때, 가장 짧은 다리 하나를 놓아 두 대륙을 연결하는 방법을 찾으시오.</p>\n<h3>입력</h3>\n<ul>\n<li>첫 줄에는 지도의 크기 N(100이하의 자연수)가 주어진다. 그 다음 N줄에는 N개의 숫자가 빈칸을 사이에 두고 주어지며, 0은 바다, 1은 육지를 나타낸다. 항상 두 개 이상의 섬이 있는 데이터만 입력으로 주어진다.</li>\n</ul>\n<h3>출력</h3>\n<ul>\n<li>첫째 줄에 가장 짧은 다리의 길이를 출력한다.</li>\n</ul>\n<h3>📍 <strong>Logic</strong></h3>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class Loc {\n  int x;\n  int y;\n  int cnt;\n\n  public Loc(int x, int y, int cnt) {\n      this.x = x;\n      this.y = y;\n      this.cnt = cnt;\n  }\n\n  public int getX() {\n      return x;\n  }\n\n  public int getY() {\n      return y;\n  }\n\n  public int getCnt() {\n      return cnt;\n  }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>각 정점별 좌표 및 현재 정점까지 오는데 필요한 다리 수를 저장하기 위해 사용하는 클래스</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">class Graph {\n  final int[][] graph;\n  boolean[][] discovered;\n  Queue&lt;Loc&gt; q = new LinkedList&lt;&gt;();\n  int[] w_way = { 1, 0, -1, 0 };\n  int[] y_way = { 0, 1, 0, -1 };\n  int bridge = Integer.MAX_VALUE;\n  int graph_size;\n  ...\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>그래프의 정보를 저장하기 위해 사용하는 클래스</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">private int buildBridge(int x, int y) {\n  discovered = new boolean[graph_size][graph_size];\n  q = new LinkedList&lt;&gt;();\n  q.add(new Loc(x, y, 0));\n  int cur_land = graph[x][y];\n  discovered[x][y] = true;\n\n  while(!q.isEmpty()) {\n    Loc loc = q.poll();\n    int cur_x = loc.getX();\n    int cur_y = loc.getY();\n    int cnt = loc.getCnt();\n\n    if (graph[cur_x][cur_y] != 0 &amp;&amp; graph[cur_x][cur_y] != cur_land) return cnt;\n\n    for (int i = 0; i &lt; 4; i++) {\n      int nextX = cur_x + w_way[i], nextY = cur_y + y_way[i];\n\n      if (nextX &lt; 0 || nextX &gt;= graph_size || nextY &lt; 0 || nextY &gt;= graph_size) continue;\n      if (discovered[nextX][nextY] || graph[nextX][nextY] == cur_land) continue;\n\n      discovered[nextX][nextY] = true;\n      q.add(new Loc(nextX, nextY, cnt+1));\n    }\n  }\n  return -1;\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>구분된 대륙 정보를 가지고, 서로 다른 대륙을 잇는 다리를 놓아보는 메소드</li>\n<li><code class=\"language-text\">if (graph[cur_x][cur_y] != 0 &amp;&amp; graph[cur_x][cur_y] != cur_land) return cnt;</code> 을 통해 서로 다른 대륙을 이은 경우 사용된 <code class=\"language-text\">다리 길이 + 1</code> 이 반환</li>\n<li>방문하지 않은 <code class=\"language-text\">0</code> , 즉 바다의 경우에만 계속 <code class=\"language-text\">Queue</code> 에 추가 </li>\n</ul>\n<h3>📄 <strong>CODE</strong></h3>\n<details>\n  <summary>코드 보기/접기💫</summary>\n    <div markdown=\"1\">\n<deckgo-highlight-code  terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">  import java.io.BufferedReader;\n  import java.io.IOException;\n  import java.io.InputStreamReader;\n  import java.util.LinkedList;\n  import java.util.Queue;\n\n  class Loc {\n      int x;\n      int y;\n      int cnt;\n\n      public Loc(int x, int y, int cnt) {\n          this.x = x;\n          this.y = y;\n          this.cnt = cnt;\n      }\n\n      public int getX() {\n          return x;\n      }\n\n      public int getY() {\n          return y;\n      }\n\n      public int getCnt() {\n          return cnt;\n      }\n  }\n\n  class Graph {\n      final int[][] graph;\n      boolean[][] discovered;\n      Queue&lt;Loc&gt; q = new LinkedList&lt;&gt;();\n      int[] w_way = { 1, 0, -1, 0 };\n      int[] y_way = { 0, 1, 0, -1 };\n      int bridge = Integer.MAX_VALUE;\n      int graph_size;\n\n      public Graph(int size) {\n          graph_size = size;\n          this.graph = new int[graph_size][graph_size];\n          discovered = new boolean[graph_size][graph_size];\n      }\n\n      public void AddElement(String line, int idx) {\n          String[] tmp = line.split(&quot; &quot;);\n          for(int i = 0; i &lt; graph_size; i++) {\n              graph[idx][i] = Integer.parseInt(tmp[i]);\n          }\n      }\n\n      public void identifyLand() {\n          int land = 2;\n          for (int i = 0; i &lt; graph_size; i++) {\n              for (int j = 0; j &lt; graph_size; j++) {\n                  if (!discovered[i][j] &amp;&amp; graph[i][j] == 1) {\n                      fillLand(i, j, land);\n                      land++;\n                  }\n              }\n          }\n      }\n\n      private void fillLand(int x, int y, int land) {\n          graph[x][y] = land;\n          discovered[x][y] = true;\n          q.add(new Loc(x, y, 0));\n\n          while(!q.isEmpty()) {\n              Loc loc = q.poll();\n              int nowX = loc.getX();\n              int nowY = loc.getY();\n\n              for (int i = 0; i &lt; 4; i++) {\n                  int nextX = nowX + w_way[i], nextY = nowY + y_way[i];\n\n                  if (nextX &lt; 0 || nextX &gt;= graph_size || nextY &lt; 0 || nextY &gt;= graph_size) continue;\n                  if (discovered[nextX][nextY]) continue;\n\n                  if (graph[nextX][nextY] == 1) {\n                      graph[nextX][nextY] = land;\n                      discovered[nextX][nextY] = true;\n                      q.add(new Loc(nextX, nextY, 0));\n                  }\n              }\n          }\n      }\n\n      public void solution() {\n          for (int i = 0; i &lt; graph_size; i++) {\n              for (int j = 0; j &lt; graph_size; j++) {\n                  if (graph[i][j] &gt; 0) {\n                      int cnt = buildBridge(i, j);\n                      if (cnt == -1) continue;\n                      bridge = Math.min(bridge, cnt);\n                  }\n              }\n          }\n          System.out.println(bridge - 1);\n      }\n\n      private int buildBridge(int x, int y) {\n          discovered = new boolean[graph_size][graph_size];\n          q = new LinkedList&lt;&gt;();\n          q.add(new Loc(x, y, 0));\n          int cur_land = graph[x][y];\n          discovered[x][y] = true;\n\n          while(!q.isEmpty()) {\n              Loc loc = q.poll();\n              int cur_x = loc.getX();\n              int cur_y = loc.getY();\n              int cnt = loc.getCnt();\n\n              if (graph[cur_x][cur_y] != 0 &amp;&amp; graph[cur_x][cur_y] != cur_land) return cnt;\n\n              for (int i = 0; i &lt; 4; i++) {\n                  int nextX = cur_x + w_way[i], nextY = cur_y + y_way[i];\n\n                  if (nextX &lt; 0 || nextX &gt;= graph_size || nextY &lt; 0 || nextY &gt;= graph_size) continue;\n                  if (discovered[nextX][nextY] || graph[nextX][nextY] == cur_land) continue;\n\n                  discovered[nextX][nextY] = true;\n                  q.add(new Loc(nextX, nextY, cnt+1));\n              }\n          }\n          return -1;\n      }\n  }\n\n  public class Main {\n      public static void main(String[] args) throws IOException {\n          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n          int N = Integer.parseInt(br.readLine());\n\n          Graph g = new Graph(N);\n\n          String line=&quot;&quot;;\n          for (int idx = 0; idx &lt; N; idx++) {\n              line = br.readLine();\n              g.AddElement(line, idx);\n          }\n\n          g.identifyLand();\n\n          g.solution();\n\n          br.close();\n      }\n  }</code>\n        </deckgo-highlight-code>\n  \t</div>\n</details>\n<h3>✏️ <strong>Review</strong></h3>\n<ul>\n<li><code class=\"language-text\">Queue</code> 에 데이터 추가, 삭제, 검색 시 사용하는 메소드들 중 유사한 기능을 하는 메소드들의 차이를 아래 참고 블로그에서 확인할 수 있었다.</li>\n<li>\n<p>섬을 구분하여 저장하고, 이후 다리를 건설할 때 섬의 가장자리부터 탐색을 시작하면 어떨까라는 생각을 했다.</p>\n<ul>\n<li>섬의 가장자리를 구분해 저장해놓고 탐색하려니, 섬의 가장자리를 구분하는 것이 문제였다.</li>\n</ul>\n</li>\n<li>섬의 가장자리를 구분하지 않고, <code class=\"language-text\">브루트 포스</code> 처럼 모든 섬의 좌표에서 탐색하는 방식으로 변경했고, <strong>메모리 초과</strong>가 발생했다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">graph[nowX][nowY] = land;\ndiscovered[nowX][nowY] = true;\n\nfor (int i = 0; i &lt; 4; i++) {\n  int nextX = nowX + w_way[i], nextY = nowY + y_way[i];\n  if (nextX &gt;= 0 &amp;&amp; nextX &lt; graph_size &amp;&amp; nextY &gt;= 0 &amp;&amp; nextY &lt; graph_size &amp;&amp; graph[nextX][nextY] == 1 &amp;&amp; !discovered[nextX][nextY]) {\n      q.add(new Loc(nextX, nextY, 0));\n  }\n}\n\n// 위 코드를 아래와 같이 변경, 메모리 초과가 발생하지 않음\n\nif (nextX &lt; 0 || nextX &gt;= graph_size || nextY &lt; 0 || nextY &gt;= graph_size) continue;\nif (discovered[nextX][nextY]) continue;\n\nif (graph[nextX][nextY] == 1) {\n  graph[nextX][nextY] = land;\n  discovered[nextX][nextY] = true;\n  q.add(new Loc(nextX, nextY, 0));\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>블로그를 참고하여 위의 코드 수정으로 메모리초과를 피할 수 있었는데, 논리적으로 이해가 가지 않는다...</li>\n</ul>\n<h3>📕 출처</h3>\n<p><a href=\"https://www.acmicpc.net/problem/2146\">https://www.acmicpc.net/problem/2146</a></p>\n<h3>참고</h3>\n<ul>\n<li><a href=\"https://goodteacher.tistory.com/112\">https://goodteacher.tistory.com/112</a></li>\n<li><a href=\"https://loosie.tistory.com/224\">https://loosie.tistory.com/224</a></li>\n</ul>","frontmatter":{"title":"👩‍💻 2146. 다리 만들기","date":"February 10, 2022","update":"February 10, 2022","tags":["그래프이론","그래프탐색","BFS"],"series":"👩‍💻 BOJ"},"fields":{"slug":"/[BOJ]2146/","readingTime":{"minutes":8.64}}},"seriesList":{"edges":[{"node":{"id":"27733333-3aad-5771-a1a1-27b4de4b4a01","fields":{"slug":"/[BOJ]2225/"},"frontmatter":{"title":"👩‍💻 2225. 합분해"}}},{"node":{"id":"548ba188-2afe-5575-b79f-107c6c65b07d","fields":{"slug":"/[BOJ]1012/"},"frontmatter":{"title":"👩‍💻 1012. 유기농 배추"}}},{"node":{"id":"0c712680-130f-5fa5-8c3b-3632dd5d1af0","fields":{"slug":"/[BOJ]1260/"},"frontmatter":{"title":"👩‍💻 1260. DFS와 BFS"}}},{"node":{"id":"0e07a592-06ce-5e01-b5e1-95398330372e","fields":{"slug":"/[BOJ]1707/"},"frontmatter":{"title":"👩‍💻 1707. 이분그래프"}}},{"node":{"id":"df12bfec-ed5c-5fc4-8442-0a4b3f9759a3","fields":{"slug":"/[BOJ]2668/"},"frontmatter":{"title":"👩‍💻 2668. 숫자 고르기"}}},{"node":{"id":"01bbb6dc-812c-5223-87c5-53bf04c0d0a6","fields":{"slug":"/[BOJ]9466/"},"frontmatter":{"title":"👩‍💻 9466. 텀 프로젝트"}}},{"node":{"id":"abc306b3-c3a6-552a-8979-e82d506b3921","fields":{"slug":"/[BOJ]2146/"},"frontmatter":{"title":"👩‍💻 2146. 다리 만들기"}}},{"node":{"id":"b3394e53-5e9a-595e-8da4-bb3debd220c0","fields":{"slug":"/[BOJ]5014/"},"frontmatter":{"title":"👩‍💻 5014. 스타트 링크"}}},{"node":{"id":"be297703-e778-5727-8019-6954bc95da3a","fields":{"slug":"/[BOJ]11559/"},"frontmatter":{"title":"👩‍💻 11559. Puyo Puyo"}}},{"node":{"id":"ddf11545-d468-5269-94b1-5daa2720e886","fields":{"slug":"/[BOJ]17471/"},"frontmatter":{"title":"👩‍💻 17471. 게리맨더링"}}},{"node":{"id":"8d77114d-fc6e-5de2-a3ca-c3b250425a56","fields":{"slug":"/[BOJ]2437/"},"frontmatter":{"title":"👩‍💻 2437. 저울"}}},{"node":{"id":"9a8942ce-552f-51ae-b304-0d0fab8f2eba","fields":{"slug":"/[BOJ]14891/"},"frontmatter":{"title":"👩‍💻 14891. 톱니바퀴"}}},{"node":{"id":"f1c04e8a-df0a-5294-949f-5f3a483cbcb0","fields":{"slug":"/[BOJ]14503/"},"frontmatter":{"title":"👩‍💻 14503. 로봇 청소기"}}},{"node":{"id":"883b6ecf-7528-5c16-92fa-edf12a64e80e","fields":{"slug":"/[BOJ]3190/"},"frontmatter":{"title":"👩‍💻 3190. 뱀"}}},{"node":{"id":"099b2576-7d05-5872-a9f0-f1ee6efd3a9a","fields":{"slug":"/[BOJ]14502/"},"frontmatter":{"title":"👩‍💻 14502. 연구소"}}},{"node":{"id":"50eef059-4e55-5f14-a9cf-fb01b6506f02","fields":{"slug":"/[BOJ]17779/"},"frontmatter":{"title":"👩‍💻 17779. 게리맨더링 2"}}},{"node":{"id":"aa67d90b-4801-574c-b225-56c23737a5e2","fields":{"slug":"/[BOJ]2579/"},"frontmatter":{"title":"👩‍💻 2579. 계단 오르기"}}},{"node":{"id":"9db6b43b-963a-5ebd-b72b-69936cf37858","fields":{"slug":"/[BOJ]14499/"},"frontmatter":{"title":"👩‍💻 14499. 주사위 굴리기"}}},{"node":{"id":"6a79cddd-dc1b-5e34-8a84-af313c37de0e","fields":{"slug":"/[BOJ]15685/"},"frontmatter":{"title":"👩‍💻 15685. 드래곤 커브"}}},{"node":{"id":"5e001d34-d985-545b-83ec-7f1c7caea286","fields":{"slug":"/[BOJ]17144/"},"frontmatter":{"title":"👩‍💻 17144. 미세먼지 안녕!"}}},{"node":{"id":"1d132410-9377-5e55-85b9-4664ff64de73","fields":{"slug":"/[BOJ]9935/"},"frontmatter":{"title":"👩‍💻 9935. 문자열 폭발"}}},{"node":{"id":"e13ff8d6-9b02-56c0-83e2-1d3144f70e1d","fields":{"slug":"/[BOJ]16472/"},"frontmatter":{"title":"👩‍💻 16472. 고냥이"}}},{"node":{"id":"0f782160-aaa9-5c54-80c0-72a15172dd16","fields":{"slug":"/[BOJ]1083/"},"frontmatter":{"title":"👩‍💻 1083. 소트"}}},{"node":{"id":"fef58615-9e18-5f50-8d09-3d1e2839342f","fields":{"slug":"/[BOJ]20922/"},"frontmatter":{"title":"👩‍💻 20922. 겹치는 건 싫어"}}},{"node":{"id":"7ca89240-c65f-5cb4-aeef-c5f1605ebd00","fields":{"slug":"/[BOJ]16172/"},"frontmatter":{"title":"👩‍💻 16172. 나는 친구가 적다(Large)"}}}]},"previous":{"fields":{"slug":"/[NextStep]6/"},"frontmatter":{"title":"📖 6장 서블릿/JSP를 활용해 동적인 웹 애플리케이션 개발하기"}},"next":{"fields":{"slug":"/[NextStep]7/"},"frontmatter":{"title":"📖 7장 DB를 활용해 데이터를 영구적으로 저장하기"}}},"pageContext":{"id":"abc306b3-c3a6-552a-8979-e82d506b3921","series":"👩‍💻 BOJ","previousPostId":"9197157a-75bc-5414-8292-da27dd69a4e1","nextPostId":"4eec34ae-1e1a-5d59-bcd1-ed5f37722bc9"}},"staticQueryHashes":[]}